package org.wenhua.yuan.and.util

import androidx.lifecycle.*
import androidx.lifecycle.Observer
import java.util.concurrent.ConcurrentHashMap
/**
 * 基于LiveData实现的 订阅/发布 事件总线 */
object LivedataBus {

    private var eventMap = ConcurrentHashMap<String, StickyLivedata<*>>()
    fun <T> with(name:String) : StickyLivedata<T> {
        var stickyLivedata = eventMap[name]
        if (stickyLivedata == null) {
            stickyLivedata = StickyLivedata<T>(name)
            eventMap.put(name, stickyLivedata)
        }

        return stickyLivedata as StickyLivedata<T>
    }


    class StickyLivedata<T>(private val eventName:String) : LiveData<T>() {

        private var mStickyData:T? = null
        private var mVersion:Int = 0
        open fun getVersion () : Int {
            return mVersion
        }
        open fun getStickyData() : T? {
            return mStickyData
        }
        override fun postValue(value: T) {
            mVersion++
            super.postValue(value)
        }

        override fun setValue(value: T) {
            mVersion++
            super.setValue(value)
        }

        fun postStickyValue (data: T) {
            mStickyData = data
            postValue(data)

        }
        fun setStickyValue (data: T) {
            mStickyData = data
            setValue(data)
        }

        override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
            observeSticky(owner, false, observer)
        }

        private fun observeSticky(owner: LifecycleOwner, sticky: Boolean, observer: Observer<in T>) {

            owner.lifecycle.addObserver(object : LifecycleEventObserver {
                // 生命周期下，拦截，并解注册
                override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                    if (event == Lifecycle.Event.ON_DESTROY) {
                        eventMap.remove(eventName)
                    }
                }

            })

            super.observe(owner, StickyBoundObserver(this@StickyLivedata, sticky, observer))
        }
    }

}

class StickyBoundObserver<T>(
    private val stickyLivedata: LivedataBus.StickyLivedata<T>,
    private val sticky: Boolean,
    private val observer: Observer<in T>
) : Observer<T> {
    // 对齐控制 -- 粘性事件，可接收注册之前发送的事件数据；
    private var mLastVersion:Int = stickyLivedata.getVersion()
    override fun onChanged(t: T) {
val m:Class<T>? = null

        // 分发前，粘性拦截，处理
        if (sticky && stickyLivedata.getStickyData() != null) {
            if (mLastVersion >= stickyLivedata.getVersion()) {// 源码中在这里，么有最新数据则直接return了
                // 没更新数据可分发时， 仅分发最后一次事件
                observer.onChanged(stickyLivedata.getStickyData())
                return
            }
        }


        mLastVersion = stickyLivedata.getVersion()
        // mLastVersion <= stickyLivedata.getVersion()
        // 不等则有最新数据可分发 包装类中实际执行分发
        observer.onChanged(t)

    }

}
